package com.startrek.ch01;

public class String2Int {

    public int string2Int(String str) {
        if (str == null || str.equals(""))
            throw new IllegalArgumentException("Input string is null or empty!");

        // TODO: handle max int and min int
        int result = 0;
        int len = str.length();
        int i = 0;
        boolean negative = false;
        if (str.charAt(0) < '0' || str.charAt(0) > '9') {
            if (str.charAt(0) == '-') {
                negative = true;
            } else if (str.charAt(0) != '+') {
                throw new IllegalArgumentException("Invalid digital string!");
            }

            if (len == 1) {
                throw new IllegalArgumentException("Invalid digital string");
            }
            i++;
        }

        while (i < len) {
            char c = str.charAt(i++);
            if (c < '0' || c > '9') {
                throw new IllegalArgumentException("Invalid digital string");
            }

            result = result * 10 + (c - '0');
        }

        return negative ? -result : result;
    }
}
